package com.rainsoftware.LicenseSystem.services;

import com.rainsoftware.LicenseSystem.models.entity.SystemUser;
import com.rainsoftware.LicenseSystem.models.entity.KeyPair;
import com.rainsoftware.LicenseSystem.utils.*;
import gaarason.database.contract.eloquent.Record;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;

@Service
public class AuthService {

    @Autowired
    private SystemUser.Model sysUserModel;

    @Autowired
    private KeyPair.Model keypairModel;

    public StandardResponse register(String username, String password, String email) {
        // Validate username and password using PasswordChecker
        if (!PasswordChecker.isUsernameValid(username)) {
            return new StandardResponse(false, HttpStatus.BAD_REQUEST, "用户名长度必须大于3小于255", null);
        }

        if (!PasswordChecker.isPasswordValid(password)) {
            return new StandardResponse(false, HttpStatus.BAD_REQUEST, "密码必须至少包含9个字符，并包含字母和数字", null);
        }

        if (sysUserModel.newQuery().where("username", username).count() > 0) {
            return new StandardResponse(false, HttpStatus.BAD_REQUEST, "用户名已经存在", null);
        }
        if (sysUserModel.newQuery().where("email", email).count() > 0) {
            return new StandardResponse(false, HttpStatus.BAD_REQUEST, "用户邮箱已经存在", null);
        }

        Record<SystemUser, Integer> record = sysUserModel.newRecord();
        SystemUser developerUser = record.getEntity();
        developerUser.setUsername(username);
        developerUser.setPassword(MD5Generator.get(password));
        developerUser.setEmail(email);
        developerUser.setAsDeveloper();
        developerUser.setCreatedAt(LocalDateTime.now());
        developerUser.setUpdatedAt(LocalDateTime.now());
        record.save();

        // Generate public/private keys
        Pair<String, String> keyPair = RSAKeyGenerator.generate();
        if (keyPair == null) {
            return new StandardResponse(false, HttpStatus.INTERNAL_SERVER_ERROR, "无法生成公私钥", null);
        }

        // Save developer public/private keys to the database
        Record<KeyPair, Integer> keyPairRecord = keypairModel.newRecord();
        keyPairRecord.getEntity().setDeveloperId(record.getEntity().getId());
        keyPairRecord.getEntity().setPubKey(keyPair.getFirst());
        keyPairRecord.getEntity().setPrivKey(keyPair.getSecond());
        keyPairRecord.save();

        return new StandardResponse(true, HttpStatus.OK, "开发者用户注册成功",
                new JSONObject().put("token", JwtUtil.generateToken(username, developerUser.getId(), developerUser.getRole())));
    }

    public StandardResponse login(String username, String password) {
        if (!PasswordChecker.isUsernameValid(username)) {
            return new StandardResponse(false, HttpStatus.BAD_REQUEST, "用户名长度必须大于3小于255", null);
        }

        if (!PasswordChecker.isPasswordValid(password)) {
            return new StandardResponse(false, HttpStatus.BAD_REQUEST, "密码必须至少包含9个字符，并包含字母和数字", null);
        }

        String md5Password = MD5Generator.get(password);

        // Find user by username and password
        Record<SystemUser, Integer> record = sysUserModel.newQuery()
                .whereAnyLike(username, "username", "email")
                .where("password", md5Password)
                .first();
        if (record == null) {
            return new StandardResponse(false, HttpStatus.UNAUTHORIZED, "用户不存在或密码不正确", null);
        }

        return new StandardResponse(true, HttpStatus.OK, "登录成功",
                new JSONObject().put("token", JwtUtil.generateToken(username, record.getEntity().getId(), record.getEntity().getRole())));
    }
}